package com.pingan.pastry.common.filter;

import com.pingan.pastry.entity.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 全局登录过滤器 注意不要加Component就 不要加 WebFilter 注解否则拦截全部请求
 */
@WebFilter(urlPatterns = "/dmpf/*", filterName = "loginFilter")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("loginFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("loginFilter doFilter...");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("text/html,");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        User user;
        if (sessionId == null || "".equals(sessionId)) {
            //跳转到登录页面
            response.sendRedirect(((HttpServletRequest) servletRequest).getContextPath() + "/index");
            return;
        } else {
            user = (User) session.getAttribute(sessionId);
        }
        if (user == null) {
            //跳转到登录页面
            response.sendRedirect(((HttpServletRequest) servletRequest).getContextPath() + "/index");
            return;
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("loginFilter destroy");
    }
}
